package com.cqyc.imview.fragment

import android.content.Intent
import android.net.Uri
import android.app.Activity
import android.os.Bundle
import android.util.Log
import android.view.View
import android.webkit.ValueCallback
import android.webkit.WebSettings
import com.cqyc.imview.JavascriptInterfaceUtils
import com.cqyc.imview.R
import com.cqyc.imview.activity.MWebActivity.Companion.URL
import com.cqyc.imview.base.BaseFragment
import com.cqyc.imview.databinding.FragmentMWebBinding
import com.cqyc.imview.model.MWebFModel
import com.cqyc.network.utils.ToastUtils
import com.cqyc.network.utils.Utils
import com.tencent.smtt.export.external.interfaces.SslError
import com.tencent.smtt.export.external.interfaces.SslErrorHandler
import com.tencent.smtt.sdk.WebChromeClient
import com.tencent.smtt.sdk.WebView
import com.tencent.smtt.sdk.WebViewClient

class MWebFragment : BaseFragment<FragmentMWebBinding, MWebFModel>() {

    override fun setLayout(): Int {
        return R.layout.fragment_m_web
    }

    private var mFilesChooserCallBack: ValueCallback<Array<Uri>>? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mViewModel.back.observe(this) {
            if ("back" == it) {
                requireActivity().finish()
            }
        }
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        val url = arguments?.getString(URL)

        val settings = mBinding.webView.settings
        settings.javaScriptEnabled = true
        settings.javaScriptCanOpenWindowsAutomatically = true
        settings.domStorageEnabled = true
        settings.mediaPlaybackRequiresUserGesture = false;
        //支持http和https混用
        settings.mixedContentMode = WebSettings.MIXED_CONTENT_ALWAYS_ALLOW
        mBinding.webView.addJavascriptInterface(
            JavascriptInterfaceUtils(
                mBinding.webView,
                mViewModel
            ), "AppBridgeJs"
        )
        mBinding.webView.webViewClient = object : WebViewClient() {
            override fun onReceivedSslError(
                p0: WebView?,
                handler: SslErrorHandler?,
                p2: SslError?
            ) {
                handler?.proceed()
            }
        }
        mBinding.webView.setDownloadListener { url, _, _, _, _ ->
            requireActivity().startActivity(Intent(Intent.ACTION_VIEW).apply {
                data = Uri.parse(url)
            })
        }
        Log.d("MWebFragment", "loadUrl-->$url")
        mBinding.webView.loadUrl(url)
        initWebView()
    }

    private fun initWebView() {
        mBinding.webView.webViewClient = object : WebViewClient() {
            override fun shouldOverrideUrlLoading(view: WebView?, url: String?): Boolean {
                if (url!!.contains(".com/yc_app/share") || url.contains(".com/app_call_back/share")) {
                    ToastUtils.showLong("分享暂未开通")
                    return true
                }
                if (url.contains("/api/v2/web/apps")) {
                    when(Utils.getValueFromUrl(url, "type")){
                        "share"->{
                            ToastUtils.showLong("share - 分享暂未开通")
                            return true
                        }
                    }
                }

                if (!url.startsWith("http")) {
                    try {
                        val intent = Intent(Intent.ACTION_VIEW, Uri.parse(url))
                        intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_SINGLE_TOP
                        requireContext().startActivity(intent)
                    } catch (_: Throwable) {
                    }
                    return true
                }

                return false
            }
        }

        mBinding.webView.webChromeClient = object : WebChromeClient() {
            override fun onShowFileChooser(
                p0: WebView?,
                filePathCallback: com.tencent.smtt.sdk.ValueCallback<Array<Uri>>?,
                p2: FileChooserParams?
            ): Boolean {
                mFilesChooserCallBack = filePathCallback
                openFileChooseProcess()
                return true
            }
        }
    }

    private fun openFileChooseProcess() {
        val i = Intent(Intent.ACTION_GET_CONTENT)
        i.addCategory(Intent.CATEGORY_OPENABLE)
        i.type = "*/*"
        val mimetypes = arrayOf("image/*")
        i.putExtra(Intent.EXTRA_MIME_TYPES, mimetypes)
        startActivityForResult(Intent.createChooser(i, "选择文件"), 0)
//        ImageHelp.takeImage(activity, object : SelectCallBack {
//            override fun selected(it: MutableList<LocalMedia>) {
//                val uri = UriUtils.file2Uri(File(it[0].compressPath))
//                if (mFilesChooserCallBack != null) {
//                    mFilesChooserCallBack!!.onReceiveValue(arrayOf(uri))
//                }
//                mFilesChooserCallBack = null
//            }
//
//            override fun onCancel() {
//                if (mFilesChooserCallBack != null) {
//                    mFilesChooserCallBack!!.onReceiveValue(arrayOf())
//                }
//                mFilesChooserCallBack = null
//            }
//        })
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        //如果是文件选择
        mFilesChooserCallBack = if (resultCode == Activity.RESULT_OK) {
            if (mFilesChooserCallBack != null) {
                mFilesChooserCallBack!!.onReceiveValue(arrayOf(data!!.data!!))
            }
            null
        } else {
            if (mFilesChooserCallBack != null) {
                mFilesChooserCallBack!!.onReceiveValue(null)
            }
            null
        }
    }
}